import 'package:ai_data_capture/bean/FlowBean.dart';
import 'package:ai_data_capture/page/main/logic.dart';
import 'package:ai_data_capture/req/api/FlowApi.dart';
import 'package:ai_data_capture/req/exp.dart';
import 'package:ai_data_capture/util/toast_util.dart';
import 'package:ai_data_capture/widget/dialog.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';

import 'state.dart';

class FlowListLogic extends GetxController {
  final FlowListState state = FlowListState();
  final parentLogic = Get.find<MainLogic>();
  @override
  void onInit() {
    super.onInit();
    init();
  }

  Future<void> init() async {
    state.flows.clear();
    state.flows.addAll(await FlowApi.getFlow());
  }

  Future<void> editFlowConfig(num? id) async {
    FlowBean? flow = state.flows.firstWhereOrNull((m) => m.id == id);
    if (flow == null) {
      showToast("没找到");
      return;
    }

    AddFlowBean? res =
        await showAddFlowDialog(parentLogic.state.fList, flow: flow);
    if (res == null) {
      return;
    }
    try {
      await FlowApi.updateFlow(res, id: flow.id);
    } catch (e) {
      showToast("添加失败");
      print(e);
    }
  }

  Future<void> runFlow(num? name) async {
    try {
      await FlowApi.runFlow(name);
      showToast("运行成功");
      init();
    } on ApiException catch (e) {
      showToast("运行失败:${e.message}");
    } on DioException catch (e) {
      showToast("运行失败:${e.message}");
    }
  }

  Future<void> deleteFlow(num? bean) async {
    try {
      await FlowApi.removeFlowById(bean);
    } catch (e) {
      showToast("删除失败:$e");
    }
    init();
  }

  Future<void> addFlow() async {
    AddFlowBean? res = await showAddFlowDialog(parentLogic.state.fList);
    if (res == null) {
      return;
    }
    try {
      await FlowApi.updateFlow(res);
    } catch (e) {
      showToast("添加失败");
      print(e);
    }
    init();
  }
}
